<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="团队名" prop="name">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item v-if="!edit" label="管理员账号" prop="username">
      <el-input v-model="form.username"></el-input>
    </el-form-item>
    <el-form-item :label="edit ? '修改管理员密码' : '密码'" prop="password">
      <el-input v-model="form.password"></el-input>
    </el-form-item>
    <!--    <el-form-item label="默认团队" prop="teamId">-->
    <!--      <el-select-->
    <!--          v-model="form.teamId"-->
    <!--          placeholder="请选择默认团队"-->
    <!--          size="large"-->
    <!--          style="width: 240px"-->
    <!--      >-->
    <!--        <el-option-->
    <!--            v-for="item in options"-->
    <!--            :key="item._id"-->
    <!--            :label="item.name"-->
    <!--            :value="item._id"-->
    <!--        />-->
    <!--      </el-select>-->
    <!--    </el-form-item>-->
    <el-form-item label="有效日期" prop="effDate">
      <el-select v-model="form.effDate" placeholder="请选择有效日期">
        <el-option label="一年" value="oneYear"></el-option>
        <el-option label="永久" value="permanent"></el-option>
      </el-select>
    </el-form-item>
<!--    <template>-->
<!--      <el-form-item label="角色" prop="role">-->
<!--        <el-radio-group v-model="form.role">-->
<!--          <el-radio label="option1">管理员</el-radio>-->
<!--          <el-radio label="option2">用户</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
<!--    </template>-->

<!--    <el-form-item label="账户余额" prop="money">-->
<!--      <el-input v-model.number="form.money"></el-input>-->
<!--    </el-form-item>-->
    <el-form-item label="团队所在地" prop="address">
      <el-input v-model="form.address"></el-input>
    </el-form-item>
    <el-form-item label="账户状态" prop="state">
      <el-switch
          v-model="form.state"
          :active-value="1"
          :inactive-value="0"
          active-text="正常"
          inactive-text="异常"
      ></el-switch>
    </el-form-item>
    <el-form-item label="上传头像" prop="thumb">
      <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="localUpload">
        <img
            v-if="form.avatar"
            :src="GETIMAGE + form.avatar"
            class="avatar"
            :style="{ maxWidth: '100%', maxHeight: '100%' }"
        />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {ElMessage, FormInstance, FormRules, UploadRequestOptions} from 'element-plus';
import {ref, PropType, onMounted, reactive} from 'vue';
import {client, GETIMAGE} from '../client';
import {db_user} from '../../../backend/src/shared/protocols/users/db_user';
import {db_team_user} from "../../../backend/src/shared/protocols/teamUser/db_team_user";
import {Plus} from "@element-plus/icons-vue";
import {db_team} from "../shared/protocols/teams/db_team";

// let options = ref([] as Array<{ _id: string; name: string; ownerId: string; avatar: string }>);
// const query = reactive({
//   username: '',
//   pageIndex: 1,
//   pageSize: 100,
// });
// // 新增一个方法来获取默认团队数据
// async function getDefaultTeam() {
//   try {
//     //如果是编辑,则根据id去查询当前默认团队和角色,并且赋值给标签页
//     // if (props.edit) {
//     //   const res = await client.callApi('', {
//     //     _id: props.data.teamId
//     //   });
//     //   options.value = res.res.data
//     // }
//     const res = await client.callApi('teams/Get', {
//       query
//     });
//     options.value = res.res.data
//   } catch (error) {
//     ElMessage.error('获取默认团队时发生错误');
//   }
// }
//
// onMounted(() => {
//   getDefaultTeam();
// });

const props = defineProps({
  data: {
    type: Object as PropType<db_user & db_team_user&db_team>,
    required: true
  },
  edit: {
    type: Boolean,
    required: false
  },
  update: {
    type: Function,
    required: true
  }
});
const defaultData = {
  _id: '',
  status: 'active',
  username: '',
  password: '',
  promotionRate: 15,
  address: '',
  money: 0,
  avatar: '/icon/human.png',
  timezone: 'Asia/Shanghai',
  state: 1,
  createTime: new Date(),
  expTime: new Date(),
  ownerId:''
};


const teamData = {
  _id: '',
  teamId: '',
  userId: '',
  name: '',
  role: '',
  effDate: '',
  status: '1',
  createTime: new Date(),
  defaultTeam: true
};


const form = ref<db_user & db_team_user &db_team& { effDate: string }>({
  ...(props.edit ? {...props.data, password: '', effDate: 'oneYear'} : {
    ...defaultData, ...teamData,
    effDate: 'oneYear'
  }),
});
const rules: FormRules = {
  name: [{required: true, message: '团队名', trigger: 'blur'}]
};
const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return false;
    let ret;
    if (!props.edit) {
      // 1.创建用户
      ret = await client.callApi('users/Add', {
        query: form.value
      });
      form.value.userId = ret.res.newID
      form.value.ownerId=ret.res.newID
      // 2.创建团队
      ret=await client.callApi('teams/Add', {
        query: form.value,
        effDate: form.value.effDate
      })
      form.value.teamId = ret.res.newID
      // 3.添加用户到团队
      await client.callApi('teamUser/Add', {
        query: form.value
      })
    } else {
      ret = await client.callApi('users/Update', {
        updateObj: form.value
      });
    }
    if (ret.isSucc) {
      ElMessage.success('保存成功！');
      props.update();
    } else {
      ElMessage.error(ret.err.message);
    }
  });
};

const localUpload = async (params: UploadRequestOptions) => {
  const ab = await params.file.arrayBuffer();
  var array = new Uint8Array(ab);
  const res = await client.callApi('upload/Upload', {
    fileName: Date.now() + '__' + params.file.name,
    fileData: array
  });
  if (res.isSucc) {
    form.value.avatar = res.res.url;
  } else {
    ElMessage.error(res.err.message);
  }
};
</script>

<style>
.avatar {
  display: block; /* 确保img作为块级元素 */
  max-width: 100%; /* 限制最大宽度为容器宽度 */
  max-height: 100%; /* 限制最大高度为容器高度 */
  margin: auto; /* 居中显示 */
  object-fit: cover; /* 保持图片宽高比并填充容器 */
}

</style>
